import asyncio
import pytest
from fastapi.testclient import TestClient
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
from main import app
from create_regions import create_regions
from config import TEST_DB_URL
from utils.db import Base
from utils.uow import UnitOfWork

test_engine = create_async_engine(TEST_DB_URL)
async_session_maker = async_sessionmaker(test_engine, expire_on_commit=False)
Base.metadata.bind = test_engine
UnitOfWork.session_factory = async_session_maker
client = TestClient(app)


@pytest.fixture(autouse=True, scope='session')
async def prepare_database():
    async with test_engine.begin() as conn:
        await conn.run_sync(Base.metadata.drop_all)
        await conn.run_sync(Base.metadata.create_all)

    await create_regions()

    async with UnitOfWork() as uow:
        await uow.regions.reset_gold()


@pytest.fixture(scope='session')
def event_loop(request):
    loop = asyncio.get_event_loop_policy().new_event_loop()
    yield loop
    loop.close()
